package com.glory.gloryquickui.view

import android.content.Context
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.glory.gloryquickui.R
import com.glory.gloryquickui.entity.FieldBean
import com.glory.gloryquickui.viewmodel.QuickUIViewModel

/**
 *计数器
 */
class CounterTextController(context: Context?,  val viewModel: QuickUIViewModel) : ViewController<FieldBean?>(context) {
    private var tvCounterName: TextView? = null
    private var tvCounterValue: TextView? = null
    private var btnDecrease: Button? = null
    private var btnPlus: Button? = null
    override fun resLayoutId(): Int {
        return R.layout.layout_counter
    }

    override fun onBindView(data: FieldBean?) {
        tvCounterName!!.text = data?.config?.label
        btnDecrease?.isEnabled = !data?.disabled!!
        btnPlus?.isEnabled = !data.disabled
        setOnclick(data)
    }

    private fun setOnclick(data: FieldBean?) {
        btnDecrease?.setOnClickListener {
            var value = tvCounterValue!!.text.toString().toInt()
            //设置最小值
            if (value < data!!.step || value <= data!!.min) {
                return@setOnClickListener
            }
            value -= data!!.step
            tvCounterValue!!.text = value.toString()
            val map = viewModel.pageData.value!!.toMutableMap()
            map[data!!.vModel] = value.toString()
            viewModel.pageData.value = map
        }
        btnPlus?.setOnClickListener {
            var value = tvCounterValue!!.text.toString().toInt()
            //设置最大值
            if (value >= data!!.max!! && data!!.max != 0){
                return@setOnClickListener
            }
            //设置最小数
            value += if (value < data!!.min!!){
                data!!.min
            }else{
                data!!.step
            }
            tvCounterValue!!.text = value.toString()
            val map = viewModel.pageData.value!!.toMutableMap()
            map[data!!.vModel] = value.toString()
            viewModel.pageData.value = map
        }
    }


    override fun onCreatedView(view: View?) {
        tvCounterName = view?.findViewById(R.id.tvCounterName)
        tvCounterValue = view?.findViewById(R.id.tvCounterValue)
        btnDecrease = view?.findViewById(R.id.btnDecrease)
        btnPlus = view?.findViewById(R.id.btnPlus)
    }

    override fun masterPart(): View? {
        return tvCounterValue
    }
}